var roleData = {};
var roleTree = $("#role-tree");

/**
 * 角色树自定义角色事件
 * @param node
 * @returns {{createItem: {label: string, action: createItem.action}, renameItem: {label: string, action: renameItem.action}, deleteItem: {label: string, action: deleteItem.action}}}
 */
function customMenu(node) {
    return {
        renameItem: {
            label: "修改角色信息",
            action: function (node) {
                var selected = roleTree.jstree("get_selected");
                var obj = roleTree.jstree("get_node", selected[0]);
                editRole(obj);
            }
        },

        deleteItem: {
            label: "删除角色",
            action: function (node) {
                var selected = roleTree.jstree("get_selected");
                var obj = roleTree.jstree("get_node", selected[0]);
                deleteRole(obj);
            }
        }
    };
}

/**
 * 初始化角色树
 */
function initRoleTree() {
    roleTree.jstree({
        core: {
            themes: {
                responsive: !1
            },
            data: function(node, callback) {
                loadRoleData(node, callback);
            }
        },
        types: {
            default: {
                icon: "fa fa-user m--font-brand"
            }
        },
        state: {
            key: "contact_tree"
        },
        contextmenu: {
            items: customMenu
        },
        plugins: ["wholerow", "types", "search", "contextmenu", "contextmenubtn", "dnd"]
    }).on('ready.jstree', function () {
        var selected = roleTree.jstree("get_selected");
        var obj = roleTree.jstree("get_node", selected[0]);
        $("#roleName").text(obj.original.text);
        changeRoleMenu();
        changeRoleUser();
        changeRoleDatapermi();
    }).on('refresh.jstree', function () {
        var selected = roleTree.jstree("get_selected");
        if (selected.length === 0) {
            roleTree.jstree("select_node", 1);
        }
    });
}

/**
 * 绑定事件
 */
function initEvent() {
    /**
     * 点击事件
     */
    roleTree.on("select_node.jstree", function (node, selected) {
        $("#roleName").empty();
        $("#roleName").text(selected.node.original.text);
        changeRoleMenu();
        changeRoleUser();
        changeRoleDatapermi();
    });

    /**
     * 页面查询
     */
    $("#search").blur("propertychange", function () {
        roleTree.jstree(true).search($.trim($(this).val()));
    });
}

jQuery(document).ready(function() {
    initRoleTree();
    initEvent();
});

/**
 * 加载角色数据
 * @param node
 * @param callback
 */
function loadRoleData(node, callback) {
    $.hcPostAjax({
        msgPrefix: '加载角色数据出错：',
        url: basePath + '/role/all/valid',
        success: function (data) {
            var treeData = [];
            var selected = true;
            if (data !== undefined || data !== null) {
                $(data).each(function () {
                    treeData.push(buildRoleNode(this, selected));
                    roleData[this.id] = this;
                    selected = false;
                });
            }
            callback.call(this, treeData);
        }
    });
}

/**
 * 组装角色节点
 * @param obj
 * @returns {{text: *, id: *, state: {opened: boolean, selected: boolean, disabled: boolean}, children: boolean}}
 */
function buildRoleNode(obj, selected) {
    return {
        text: obj.name,
        a_attr:{"title": obj.code},
        id: obj.id,
        state: {
            'opened': true,  //表示是否立即打开
            'selected': selected, //是否选中，这边可以支持表达式，函数等
            "disabled": false //是否禁用，这边可以支持表达式，函数等
        },
        children: false   //表示是否还有子节点
    };
}

/**
 * 新增角色
 * @param node
 */
function addRole() {
    layer.open({
        title: '新建角色',
        type: 1,
        maxmin: true,
        area: ['60%', '80%'],
        shadeClose: true,
        content: $("#editRoleTemplate").html(),
        success: function(layero, index){
            /**
             * 保存角色
             */
            form.on('submit(save_role)', function(data){
                saveRole('新增角色');
            });

            /**
             * 取消修改
             */
            $(".edit_cancle").on("click", function () {
                layer.closeAll();
            });
        }
    });
}

/**
 * 修改角色
 * @param node
 */
function editRole(node) {
    layer.open({
        title: '修改角色',
        type: 1,
        maxmin: true,
        area: ['60%', '80%'],
        shadeClose: true,
        content: $("#editRoleTemplate").html(),
        success: function(layero, index){
            var temp_role = roleData[node.id];
            $("#edit_role_id").val(temp_role.id);
            $("#edit_role_name").val(temp_role.name);
            $("#edit_role_code").val(temp_role.code);
            $("#edit_role_description").val(temp_role.description);
            $("#edit_role_isPublic").val(temp_role.isPublic);
            /**
             * 保存角色
             */
            form.on('submit(save_role)', function(data){
                saveRole('修改角色');
            });

            /**
             * 取消修改
             */
            $(".edit_cancle").on("click", function () {
                layer.closeAll();
            });
        }
    });
}

/**
 * 删除角色
 * @param node
 */
function deleteRole(node) {
    layer.confirm('确定删除<font color="red">[' + node.text + ']</font>？', {
        icon: 3,
        title: '提示',
        btn: ['确定','取消'] //按钮
    }, function(index){
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '删除角色出错：',
            url: basePath + '/role/delete',
            data: {id: node.id},
            success: function (data) {
                layer.msg('角色删除成功！', {icon: 1,time:1500}, function () {
                    roleTree.jstree(true).refresh();
                });
            }
        })
    }, function(index){
        layer.close(index);
    });
}

/**
 * 保存角色
 */
function saveRole(type) {
    var data = {
        id: $("#edit_role_id").val(),
        name: $.trim($("#edit_role_name").val()),
        code: $.trim($("#edit_role_code").val()),
        description: $.trim($("#edit_role_description").val()),
        isPublic: $.trim($("#edit_role_isPublic").val())
    };
    $.hcPostAjax({
        showLoad: true,
        msgPrefix: type + '出错',
        url: basePath + '/role/addOrUpdate',
        data: data,
        success: function (data) {
            layer.msg(type + '成功！', {icon: 1,time:1500}, function () {
                roleTree.jstree(true).refresh();
                layer.closeAll();
            });
        }
    });
}